package com.future.lock.mall;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.future.lock.R;
import com.future.lock.common.Constants;
import com.future.lock.common.MyApp;
import com.future.lock.common.http.HttpUtils;
import com.future.lock.mall.activity.OrderConfirmActivity;
import com.future.lock.mall.entity.beans.GoodDetailsBean;
import com.future.lock.mall.entity.response.GoodDetailsBeanResponse;
import com.future.lock.mall.widgets.MyScrollView;
import com.future.lock.mall.widgets.PullUpToLoadMore;
import com.future.lock.me.activity.LoginActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * 商城Fragment
 */
public class MallFragment extends Fragment {

    Unbinder unbinder;
    @BindView(R.id.ptlm)
    PullUpToLoadMore ptlm;
    @BindView(R.id.advertsImgView)
    ImageView advertsImgView;
    @BindView(R.id.pullTipsTextView)
    TextView pullTipsTextView;
    @BindView(R.id.topScrollView)
    MyScrollView topScrollView;
    @BindView(R.id.priceTextView)
    TextView priceTextView;
    @BindView(R.id.webView)
    WebView webView;

    GoodDetailsBean goodDetailsBean;

    public MallFragment() {
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mall, container, false);
        unbinder = ButterKnife.bind(this, view);
        initWebView();
        return view;
    }

    private void initWebView() {
        if (this.webView != null) {
            final WebSettings settings = this.webView.getSettings();
            settings.setUseWideViewPort(false);
            settings.setAllowFileAccess(true);
            settings.setSupportZoom(true); // 支持缩放
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);//把html中的内容放大webview等宽的一列中
            settings.setLoadWithOverviewMode(true);
            settings.setJavaScriptEnabled(true);
            // 设置缓存模式为不缓存
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            // 设置启用Dom Storage
            settings.setDomStorageEnabled(true);
            this.webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    webView.post(() -> {
                        imgReset();//重置webview中img标签的图片大小
                    });
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    view.loadUrl(url);
                    return true;
                }

                /**
                 * 对图片进行重置大小，宽度就是手机屏幕宽度，高度根据宽度比便自动缩放
                 **/
                private void imgReset() {
                    try {
                        webView.loadUrl("javascript:(function(){" + "var objs = document.getElementsByTagName('img'); " + "for(var i=0;i<objs.length;i++)  " + "{" + "var img = objs[i];   " + "    img.style.maxWidth = '100%'; img.style.height = 'auto';  " + "}" + "})()");
                    }
                    catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getGoodsDetailsBean();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    private void getGoodsDetailsBean() {
        if (goodDetailsBean == null) {
            HttpUtils.getHttpApi()
                    .getGoodsInfo("")
                    .enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            GoodDetailsBeanResponse beanResponse = new GoodDetailsBeanResponse();
                            beanResponse.parse(response.body());
                            if (beanResponse.success == 1) {
                                goodDetailsBean = beanResponse.data;
                                updateUis();
                            }
                            else {
                                Toast.makeText(getContext(), "获取商品详情失败:" + beanResponse.msg, Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                            Toast.makeText(getContext(), "获取商品详情失败:" + t.getMessage(), Toast.LENGTH_SHORT)
                                    .show();
                        }
                    });
        }
    }

    private void updateUis() {
        if (goodDetailsBean != null && this.webView != null) {
            Glide.with(this)
                    .load(goodDetailsBean.getAdverts_img())
                    .dontAnimate()
                    .into(this.advertsImgView);

            this.priceTextView.setText(String.format("¥%.2f购买", this.goodDetailsBean.getPrice()));
            this.webView.loadDataWithBaseURL(Constants.BASE_URL, this.goodDetailsBean.getGoods_desc(), "text/html", "utf-8", null);
        }
    }

    @OnClick(R.id.buyMeView)
    protected void buyMe() {
        if (MyApp.hasLogin()) {
            Intent intent = new Intent(getActivity(), OrderConfirmActivity.class);
            intent.putExtra(OrderConfirmActivity.GOODS_BEAN_KEY, this.goodDetailsBean);
            startActivity(intent);
        }
        else {
            startActivity(new Intent(getContext(), LoginActivity.class));
        }
    }
}
